<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: CropAspect.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Instruction_CropAspect extends Zimm_Model_DbTable_Instruction_Abstract
{
    /**
     * Crop image to specified aspect ratio.
     *
     * @param resource $image GD resource
     * @param string $savePath Target save path
     * @param array $params Instruction arguments
     * @return boolean Indicates if image was altered
     */
    protected function _process(&$image, $savePath, $params)
    {
        if (isset($params['aspect'])) {
            $toWidth = $fromWidth = imagesx($image);
            $toHeight = $fromHeight = imagesy($image);
            $fromAspect = $fromWidth / $fromHeight;

            $toAspect = (float)$params['aspect'];
            if ($fromAspect > $toAspect) {
                $toWidth = (int)($fromWidth / ($fromAspect / $toAspect));
            } else {
                $toHeight = (int)($fromHeight / ($toAspect / $fromAspect));
            }

            $weight = isset($params['weight']) ? max(0, min(1, (float)$params['weight'])) : 0.5;

            if ($toHeight != $fromHeight || $toWidth != $fromWidth) {
                $im_dest = imagecreatetruecolor($toWidth, $toHeight);
                imagealphablending($im_dest, false);
                imagecopy($im_dest, $image, 0, 0, ($fromWidth - $toWidth) * $weight,
                        ($fromHeight - $toHeight) * $weight, $toWidth, $toHeight);
                imagedestroy($image);
                $image = $im_dest;
                return true;
            }
        }
        return false;
    }
}